package com.yzt.dynamicmodule.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.yzt.dynamicmodule.dialog.AddressGoOnDialog;
import com.yzt.dynamicmodule.dialog.IndexShareDialog;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.zhuju.activity.BaseViewBindingActivity;
import com.yzt.zhuju.arouter.RouterDynamic;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.arouter.RouterUser;
import com.yzt.zhuju.dialog.BaseDialog;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.game.GameDetailBean;
import com.yzt.zhuju.network.entity.game.GameUserListBean;
import com.yzt.zhuju.photoview.PhotoViewManager;
import com.yzt.zhuju.utils.BarUtils;
import com.yzt.zhuju.utils.SpannableFactory;
import com.yzt.zhuju.utils.ViewUtil;
import com.yzt.zhuju.utils.ViewUtils;
import com.yzt.zhuju.utils.recyclerutils.GridItemDecoration;
import com.yzt.zhuju.voice.VoicePlayManager;
import com.yzt.zhuju.widget.PageIndicatorView;
import com.yzt.dynamicmodule.R;
import com.yzt.dynamicmodule.adapter.ActivityDetailButtonAdapter;
import com.yzt.dynamicmodule.adapter.ActivityDetailUserAdapter;
import com.yzt.dynamicmodule.banner.BannerViewHolder;
import com.yzt.dynamicmodule.databinding.ActivityGameDetailBinding;
import com.yzt.p_base.AppUtils;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.opensource.svgaplayer.SVGAImageView;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.util.ArrayList;
import java.util.List;

import cn.jzvd.Jzvd;

/**
 * 作者：bobwang
 * 创建时间：2023-10-11 22:50:27
 * 描述：活动详情
 */
@SuppressLint("SetTextI18n")
@Route(path = RouterDynamic.ACTIVITY_GAME_DETAIL)
public class GameDetailActivity extends BaseViewBindingActivity<ActivityGameDetailBinding> implements View.OnClickListener {

    @Autowired
    String gameId;

    private Toolbar toolbar;

    /**
     * 轮播图
     */
    private MZBannerView<String> bannerView;
    private PageIndicatorView indicatorView;

    private SVGAImageView svgaPersonalHomeDecoration;

    private PhotoViewManager photoViewManager;

    private final List<String> albums = new ArrayList<>();

    @Override
    public boolean hideTitleBar() {
        return true;
    }

    @NonNull
    @Override
    public ActivityGameDetailBinding generateViewBinding() {
        return ActivityGameDetailBinding.inflate(getLayoutInflater());
    }

    /**
     * 获取状态栏高度
     */
    private void initTitleContainerMargin() {
        RelativeLayout rlTitleContainer = findViewById(R.id.person_title_layout);
        Toolbar.LayoutParams ll = (Toolbar.LayoutParams) rlTitleContainer.getLayoutParams();
        ll.setMargins(0, ViewUtils.getStatusBarHeight(this), 0, 0);
        rlTitleContainer.setLayoutParams(ll);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.setStatusBarLightMode(this, true);
        BarUtils.setStatusBarAlpha(this, 0);
        ARouter.getInstance().inject(this);
        initTitleContainerMargin();
        photoViewManager = PhotoViewManager.getInstance(AppUtils.getApp());

        // 页面滑动监听
        loadScrollView();

        // 初始轮播图
        initBannerView();

        // 初始化上下监听
        initListener();

        initRecycle();
    }

    private ActivityDetailUserAdapter adapterUser;
    private ActivityDetailButtonAdapter adapterButton;

    private void initRecycle() {
        viewBinding.recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        viewBinding.recyclerView.addItemDecoration(new GridItemDecoration.Builder()
                .divider(20)
                .build());
        adapterUser = new ActivityDetailUserAdapter();
        viewBinding.recyclerView.setAdapter(adapterUser);
        adapterUser.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                GameUserListBean item = adapterUser.getItem(position);
                RouterUser.PersonalDetailActivity(item.getUserId());
            }
        });

        viewBinding.recyclerButton.setLayoutManager(new LinearLayoutManager(this));
        adapterButton = new ActivityDetailButtonAdapter();
        viewBinding.recyclerButton.setAdapter(adapterButton);
        adapterButton.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String item = adapterButton.getItem(position);
//        需要显示的按钮枚举 [ 1：修改活动，2：取消活动，3：立即加入，4：进入房间，5：活动已结束，6：退出活动，
//        7：成员已满，无法加入，8：活动进行中，无法加入，9：活动已取消，90：请下载煮桔APP进入房间 ]
                if (item.equals("1")) {
                    GameAddActivity.startSelf(GameDetailActivity.this, gameId);
                } else if (item.equals("2")) {
                    cancelGame();
                } else if (item.equals("3")) {
                    joinGame();
                } else if (item.equals("4")) {
                    enterRoom();
                } else if (item.equals("5")) {

                } else if (item.equals("6")) {
                    quitGame();
                }
            }
        });
    }

    /**
     * 页面滑动处理
     */
    private void loadScrollView() {

        toolbar = findViewById(R.id.toolbar);

        NestedScrollView scrollView = findViewById(R.id.scrollView);

        scrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {

            int offsetHeight = 300;

            if (scrollY > offsetHeight) {
                toolbar.setBackgroundColor(ContextCompat.getColor(GameDetailActivity.this, R.color.white));
                viewBinding.titleLeftIv.setImageResource(R.mipmap.icon_back_black);
                viewBinding.titleMoreIv.setImageResource(R.mipmap.icon_activity_share);

            } else {
                toolbar.setBackgroundColor(changeAlpha(ContextCompat.getColor(GameDetailActivity.this, R.color.white),
                        Math.abs(scrollY * 1.0f) / offsetHeight));
                viewBinding.titleLeftIv.setImageResource(R.mipmap.icon_back_white);
                viewBinding.titleMoreIv.setImageResource(R.mipmap.icon_activity_share);

            }
        });
    }

    /**
     * banner栏
     */
    private void initBannerView() {
        indicatorView = findViewById(R.id.indicator);
        bannerView = findViewById(R.id.banner_view);
        bannerView.setIndicatorAlign(MZBannerView.IndicatorAlign.CENTER);
        bannerView.setBannerPageClickListener((view, position) -> {
            if (albums == null || albums.size() == 0) {
                return;
            }
            List<String> list = new ArrayList<>();
            List<String> newList = new ArrayList<>(albums);
            for (String album : newList) {
                list.add(ImageLoadUtil.url2Webp(album));
            }
            newList.clear();
            photoViewManager.showPhotoView(view, list, position);
        });

        bannerView.addPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                indicatorView.setPersonalSelectedPage(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        initAlbum();
    }

    /**
     * 顶部和底部监听注册
     */
    public void initListener() {
        viewBinding.titleLeftLayout.setOnClickListener(this);
        viewBinding.titleMoreIv.setOnClickListener(this);
        viewBinding.tvFeeDetail.setOnClickListener(this);
        viewBinding.imgMapTo.setOnClickListener(this);
        viewBinding.titleMoreIv.setImageResource(R.mipmap.icon_activity_share);
    }

    /**
     * 根据百分比改变颜色透明度
     */
    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

    /**
     * 获取页面数据
     * 缓存数据 - 网络请求
     */
    public void getPageData() {
        JSONObject json = new JSONObject();
        json.put("activityId", gameId);
        BizLayer.getInstance().getDynamicModule().getGameDetail(json, new AresSubscriber<GameDetailBean>() {
            @Override
            protected void onSuccess(GameDetailBean bean) {
                try {
                    initData(bean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 加载相册
     */
    private void initAlbum() {
        indicatorView.setVisibility(albums.size() > 1 ? View.VISIBLE : View.GONE);
        indicatorView.initPersonalIndicator(albums.size());
        bannerView.setIndicatorVisible(false);
        bannerView.setPages(albums, (MZHolderCreator<BannerViewHolder>) BannerViewHolder::new);
        bannerView.setCanLoop(false);
    }

    /**
     * 加载用户信息
     */
    public void initData(GameDetailBean bean) {
        if (bean.getActivityStatus() == 30 || bean.getActivityStatus() == 40) {
            //[ 0：未付款(创建活动为我付款时候)，10：未开始，20：进行中，30：活动结束，40：活动取消 ]
            viewBinding.titleMoreIv.setVisibility(View.GONE);
        }
        if (bean.getCover() != null) {
            albums.add(bean.getCover());
        } else {
            albums.add(bean.getActivityFileUrl());
        }
        initAlbum();
        viewBinding.tvPersonName.setText(bean.getActivitySubject());
        viewBinding.tvTime.setText(bean.getStartTime() + "~" + bean.getEndTime());
        viewBinding.tvUserDesc.setText(bean.getDsc());
        // 付款人类型 （谁付款 [ 1：男士付款，2：女士付款，3：我付款 ]
        String payerType = bean.getPayerType() == 1 ? "男士付" : (bean.getPayerType() == 2 ? "女士付" : "发起人付");
        viewBinding.tvPrice.setText(SpannableFactory.create(bean.getUnitPrice() + "/人")
                .append(bean.getTimeStr() + "    ")
                .append(payerType)
                .foregroundResColor(R.color.color_7CA6F9)
                .build());

        viewBinding.tvAddress.setText(bean.getAddress());
        viewBinding.tvAddressDetail.setText(bean.getCityName());

        if (bean.getTotalPeopleNum() == bean.getList().size()) {
            viewBinding.tvPersonalNum.setText(bean.getTotalPeopleNum() + "人");
        } else if (bean.getTotalPeopleNum() - bean.getList().size() < 0) {
            viewBinding.tvPersonalNum.setText("已参与" + bean.getTotalPeopleNum() + "人");
        } else {
            viewBinding.tvPersonalNum.setText("已参与" + bean.getTotalPeopleNum() + "人，剩余" + (bean.getTotalPeopleNum() - bean.getList().size()) + "人待参与");
        }

        adapterUser.setList(bean.getList());
        adapterButton.setList(bean.getButtonList());
    }

    @Override
    public void onClick(View view) {

        if (ViewUtil.isFastDoubleClick()) {
            return;
        }
        if (view.getId() == R.id.title_left_layout) {
            finish();
        }

        if (view.getId() == R.id.title_more_iv) {
            // 分享
            IndexShareDialog share = (IndexShareDialog) BaseDialog.showDialog(this, IndexShareDialog.class);
            share.setListener(new IndexShareDialog.OnSelectOnClickListener() {
                @Override
                public void onShare(int type) {
                    ToastUtil.showMessage("分享");
                }
            });
        }

        if (view.getId() == R.id.tv_fee_detail) {
            RouterMain.goToWeb("https://www.baidu.com");
        }

        if (view.getId() == R.id.img_map_to) {
            // 位置
            AddressGoOnDialog dialog = (AddressGoOnDialog) BaseDialog.showDialog(this, AddressGoOnDialog.class);
            dialog.setListener(new AddressGoOnDialog.OnSelectOnClickListener() {
                @Override
                public void onShare(int type) {
                    StringBuffer stringBuffer = new StringBuffer("baidumap://map/navi?location=")
                            .append("28.680242").append(",").append("115.980541").append("&type=TIME");
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(stringBuffer.toString()));
                    intent.setPackage("com.baidu.BaiduMap");
                    startActivity(intent);
                }
            });
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.goOnPlayOnPause();
        VoicePlayManager.getInstance().stopPlay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bannerView != null) {
            bannerView.pause();
        }
        if (svgaPersonalHomeDecoration != null) {
            svgaPersonalHomeDecoration.stopAnimation();
            svgaPersonalHomeDecoration.clear();
            svgaPersonalHomeDecoration = null;
        }
        if (photoViewManager != null) {
            photoViewManager.clear();
            photoViewManager = null;
        }
    }

    /**
     * 加入游戏
     */
    public void joinGame() {
        JSONObject json = new JSONObject();
        json.put("activityId", gameId);
        BizLayer.getInstance().getDynamicModule().joinGame(json, new AresSubscriber<Object>() {
            @Override
            protected void onSuccess(Object bean) {
                getPageData();
                GameActivity.startSelf(GameDetailActivity.this, gameId);
                finish();
            }
        });
    }

    /**
     * 退出
     */
    public void quitGame() {
        JSONObject json = new JSONObject();
        json.put("activityId", gameId);
        BizLayer.getInstance().getDynamicModule().quitGame(json, new AresSubscriber<Object>() {
            @Override
            protected void onSuccess(Object bean) {
                getPageData();
            }
        });
    }

    /**
     * 取消游戏
     */
    public void cancelGame() {
        JSONObject json = new JSONObject();
        json.put("activityId", gameId);
        BizLayer.getInstance().getDynamicModule().cancelGame(json, new AresSubscriber<Object>() {
            @Override
            protected void onSuccess(Object bean) {
                getPageData();
            }
        });
    }

    /**
     * 进入房间
     */
    public void enterRoom() {
        JSONObject json = new JSONObject();
        json.put("activityId", gameId);
        BizLayer.getInstance().getDynamicModule().enterRoom(json, new AresSubscriber<Object>() {
            @Override
            protected void onSuccess(Object bean) {
                GameActivity.startSelf(GameDetailActivity.this, gameId);
                finish();
            }
        });
    }

    /**
     * 踢出用户
     */
    public void kickUser(String userId, int position) {
        JSONObject json = new JSONObject();
        json.put("activityId", gameId);
        json.put("kickUser", userId);
        BizLayer.getInstance().getDynamicModule().gameKickUser(json, new AresSubscriber<Object>() {
            @Override
            protected void onSuccess(Object bean) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getPageData();
    }
}
